package platform.resource;

import common.struct.ActorInfo;
import common.struct.ValueType;
import com.alibaba.fastjson.JSONObject;
import common.struct.State;
import platform.app.AppMgr;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ActorMgr {
    private final String actorName;
    private ValueType actorType;
    private boolean isAlive = true;
    private final Set<AppMgr> apps = ConcurrentHashMap.newKeySet();

    public ActorMgr(JSONObject object) {
        actorName = object.getString("name");
        try {
            actorType = ValueType.fromString(object.getString("valueType"));
        } catch (Exception e) {
            actorType =ValueType.STRING;
        }
    }

    public String getActorName() {
        return actorName;
    }

    public ValueType getActorType() {
        return actorType;
    }

    public void addApp(AppMgr app) {
        this.apps.add(app);
    }

    public void removeApp(AppMgr app) {
        this.apps.remove(app);
    }

    public Set<AppMgr> getApps() {
        return apps;
    }

    public List<String> getAppsName() {
        List<String> appsName = new ArrayList<>();
        for (AppMgr app : apps) {
            if (!app.getAppName().equals("WebServer")) {
                appsName.add(app.getAppName());
            }
        }
        return appsName;
    }

    public void setAlive(boolean isAlive) {
        this.isAlive = isAlive;
    }

    public boolean isAlive() {
        return isAlive;
    }

    @Override
    public String toString() {
        return new ActorInfo(actorName, actorType, isAlive ? State.ON : State.OFF, getAppsName()).toString();
    }
}
